<?php

declare (strict_types=1);

namespace app\api\validate;

use think\Validate;

class UserValidate extends Validate
{
    protected $rule = [
        'username' => 'require|checkChineseName',
        'real_name' => 'require|checkChineseName',
        'id_card'  => 'require|id_card',
        'phone' => 'require|mobile|unique:user',
        'password' => 'require|min:8',
        'code' => 'require',
        'nickname' => 'require|max:32',
        'sex' => 'require',
        'birth_date' => 'require|date',
        'avatar' => 'require',
        'email' => 'email',
        'area' => 'require',
        'photos' => 'require',
        'country' => 'require',
        'status' => 'require',
    ];

    protected $message = [
        'phone.require' => '请填写手机号码',
        'phone.mobile' => '手机号码格式错误',
        'phone.unique' => '手机号已存在',
        'password.require' => '请填写密码',
        'password.min' => '密码不能低于8个字符',
        'code.require' => '请填写验证码',
        'username.require' => '姓名不能为空',
        'username.checkChineseName' => '姓名必须为2-10个中文字符',
        'id_card.require' => '身份证号不能为空',
        'id_card.id_card' => '身份证号格式错误'
    ];

    // 自定义验证姓名
    protected function checkChineseName($value): bool
    {
        return preg_match('/^[\x{4e00}-\x{9fa5}]{2,10}$/u', $value) === 1;
    }

    // 登录验证场景
    public function sceneLogin(): UserValidate
    {
        return $this->only(['phone', 'code'])
            ->remove('phone', 'unique');
    }

    // 身份验证
    public function sceneidCard(): UserValidate
    {
        return $this->only(['id_card', 'real_name']);
    }

    // 发送验证码
    public function sceneSendCode(): UserValidate
    {
        return $this->only(['phone'])
            ->remove('phone', 'unique');
    }

    // 心动验证
    public function heartbeat(): UserValidate
    {
        return $this->only(['min_age', 'max_age', 'lng', 'lat', 'km'])
            ->append('lng', 'require|float')
            ->append('lat', 'require|float')
            ->append('km', 'require|number')
            ->append('min_age', 'require|number|between:18, 120')
            ->append('max_age', 'require|number|between:18, 120');
    }

    // 使用场景
    protected $scene = [
        'userProfile' => ['nickname', 'username', 'country', 'birth_date', 'sex', 'email', 'area'], // 用户基础信息
    ];
}